#include<cstring>
#include<iostream>
#include<string>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include"log.hpp"

#define TEMP
log l;

void Usage()
{
    std::cout<<"proce ip port"<<std::endl;
}

int main(int argc,char* argv[])
{
    #ifdef TEMP
    std::string ClientIp="113.45.231.111";
    // std::string ClientIp="127.0.0.1";
    uint16_t ClientPort=8080;
    #else
    if(argc!=3)
    {
        Usage();
        exit(-1);
    }
    std::string ClientIp=argv[1];
    uint16_t ClientPort=std::stoi(argv[2]);
    #endif

    int sockfd=socket(AF_INET,SOCK_STREAM,0);

    struct sockaddr_in in;
    in.sin_addr.s_addr=inet_addr(ClientIp.c_str());
    in.sin_port=htons(ClientPort);
    in.sin_family=AF_INET;

    //与服务器进行链接
    int cnt=5;  
    int n;  //记录connect的返回值，判断是否连接失败
    socklen_t len=sizeof(in);
    while(cnt--)
    {
        n=connect(sockfd,reinterpret_cast<struct sockaddr*> (&in),len);
        std::cout<<n<<std::endl;    //临时测试

        if(n<0) 
        {
            l(comm,"connect连接失败,errno:%d,strerror:%s\n正在尝试重连...",errno,strerror(errno));
            sleep(1);
            continue;
        }
        else if(n==0)    break;

    }
    if(cnt==0&&n==-1)
    {
        l(err,"网络异常connect连接失败,程序退出");
        exit(-1);
    }   
    else    l(info,"connect连接成功");
    
    //开始通信
    char buffer[size];
    while(true)
    {
        std::string message;
        getline(std::cin,message);
        int n = write(sockfd,message.c_str(),message.size());
        if(n<0) l(err,"write写入失败，errno:%d,strerror:%s",errno,strerror(errno));
        else    l(info,"write写入成功");


    }


    close(sockfd);
    return 0;
}